<script lang="ts">
export default {
  name: "sql"
};
</script>

<script setup lang="ts">
import dayjs from "dayjs";
import { getList, remove, get, add, update } from "/@/api/system/datasource";
import { FormInstance } from "element-plus";
import { reactive, ref, onMounted, toRaw, computed } from "vue";
import { EpTableProBar } from "/@/components/ReTable";
import { message } from "@pureadmin/components";
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { FormRules } from "element-plus/es";
import { ResponseType } from "/@/utils/http";
import { ReTextHighlight } from "/@/components/ReTextHighlight";

const form = reactive({
  dataSourceName: ""
});

const editForm = ref({
  id: null,
  dataSourceName: "",
  url: "",
  username: "",
  password: "",
  driverClassName: ""
});
const editRules = reactive<FormRules>({
  dataSourceName: [{ required: true, message: "数据源名不能为空" }],
  url: [{ required: true, message: "连接url不能为空" }],
  username: [{ required: true, message: "用户名不能为空" }],
  driverClassName: [{ required: true, message: "驱动名称不能为空" }]
});

let dataList = ref([]);
let pageSize = ref(10);
let pageNum = ref(1);
let totalPage = ref(0);
let loading = ref(true);
let editLoading = ref(false);
let editId = ref(null);
let editShow = ref(false);

const formRef = ref<FormInstance>();
const editFormRef = ref<FormInstance>();

let isUpdate = computed(() => editId.value != null);

const onSubmit = async () => {
  await editFormRef.value.validate((valid, fields) => {
    if (valid) {
      const data: any = toRaw(editForm.value);
      editLoading.value = true;
      let resp: ResponseType;
      if (isUpdate.value) {
        resp = update(data);
      } else {
        resp = add(data);
      }
      resp
        .then(resp => {
          if (resp.code === 200) {
            message.success(resp.msg);
            editShow.value = false;
            onSearch();
          } else {
            message.error(resp.msg);
          }
        })
        .finally(() => (editLoading.value = false));
    }
  });
};

function handleUpdate(row) {
  editFormRef.value?.resetFields();
  editId.value = row.id;
  editLoading.value = true;
  get(row.id)
    .then(res => {
      const { id, dataSourceName, url, username, password, driverClassName } =
        res.data;
      editForm.value = {
        id,
        dataSourceName,
        url,
        username,
        password,
        driverClassName
      };
    })
    .finally(() => (editLoading.value = false));
  editShow.value = true;
}

function handleDelete(row) {
  loading.value = true;
  remove(row.id).then(resp => {
    if (resp.code === 200) {
      message.success(resp.msg);
      onSearch();
    } else {
      message.error(resp.msg);
    }
  });
}

function handleCurrentChange(val: number) {
  pageNum.value = val;
  onSearch();
}

function handleSizeChange(val: number) {
  pageSize.value = val;
  onSearch();
}

function handleSelectionChange(val) {
  console.log("handleSelectionChange", val);
}

async function onSearch() {
  loading.value = true;
  let { data } = await getList({
    dataSourceName: form.dataSourceName,
    pageSize: pageSize.value,
    pageNum: pageNum.value
  });
  dataList.value = data?.list;
  totalPage.value = data?.total;
  setTimeout(() => {
    loading.value = false;
  }, 500);
}

const resetForm = (formEl: FormInstance | undefined) => {
  pageNum.value = 1;
  pageSize.value = 10;
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};

function handleAdd() {
  editFormRef.value?.resetFields();
  editId.value = null;
  editShow.value = true;
}

onMounted(() => {
  onSearch();
});
</script>

<template>
  <div class="main">
    <re-dialog
      v-model="editShow"
      :title="editId === null ? '数据源添加' : '数据源修改'"
    >
      <el-form
        :model="editForm"
        :label-width="100"
        ref="editFormRef"
        :rules="editRules"
        v-loading="editLoading"
      >
        <el-form-item label="数据源名：" prop="dataSourceName" required>
          <el-input v-model="editForm.dataSourceName" clearable />
        </el-form-item>
        <el-form-item label="连接url：" prop="url" required>
          <el-input v-model="editForm.url" clearable />
        </el-form-item>
        <el-form-item label="用户名：" prop="username" required>
          <el-input v-model="editForm.username" clearable />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="editForm.password" clearable />
        </el-form-item>
        <el-form-item label="驱动名称：" prop="driverClassName" required>
          <el-input v-model="editForm.driverClassName" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" style="width: 100px" @click="onSubmit">{{
            editId === null ? "添加" : "修改"
          }}</el-button>
          <el-button @click="editShow = false" style="width: 100px"
            >取消</el-button
          >
        </span>
      </template>
    </re-dialog>

    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="bg-white pl-8 pt-4"
    >
      <el-form-item label="数据源名：" prop="dataSourceName">
        <el-input
          v-model="form.dataSourceName"
          placeholder="请输入数据源名"
          clearable
          class="form-item-input"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('search')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon('refresh')" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <EpTableProBar
      title="数据源列表"
      :loading="loading"
      :dataList="dataList"
      @refresh="onSearch"
    >
      <template #buttons>
        <el-button
          type="primary"
          :icon="useRenderIcon('add')"
          @click="handleAdd"
        >
          添加
        </el-button>
      </template>
      <template v-slot="{ size }">
        <el-table
          border
          table-layout="auto"
          :size="size"
          :data="dataList"
          :header-cell-style="{ background: '#fafafa', color: '#606266' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            label="数据源名"
            align="center"
            prop="dataSourceName"
            width="120"
            fixed="left"
          >
            <template #default="scope">
              <ReTextHighlight
                :content="scope.row.dataSourceName"
                :searchText="form.dataSourceName"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="连接url"
            align="center"
            prop="url"
            min-width="150"
          />
          <el-table-column
            label="用户名"
            align="center"
            prop="username"
            width="100"
          />
          <el-table-column
            label="密码"
            align="center"
            prop="password"
            width="100"
          />
          <el-table-column
            label="驱动名称"
            align="center"
            prop="driverClassName"
            width="200"
          />
          <el-table-column
            label="更新时间"
            align="center"
            width="180"
            prop="updateTime"
            :formatter="
              ({ updateTime }) => {
                return dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss');
              }
            "
          />
          <el-table-column
            fixed="right"
            label="操作"
            width="150"
            align="center"
          >
            <template #default="scope">
              <el-button
                class="reset-margin"
                type="text"
                :size="size"
                @click="handleUpdate(scope.row)"
                :icon="useRenderIcon('edits')"
              >
                修改
              </el-button>
              <el-popconfirm
                title="是否确认删除?"
                @confirm="handleDelete(scope.row)"
              >
                <template #reference>
                  <el-button
                    class="reset-margin"
                    type="text"
                    :size="size"
                    :icon="useRenderIcon('delete')"
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="flex justify-end mt-4"
          :small="size === 'small'"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
          :current-page="pageNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </template>
    </EpTableProBar>
  </div>
</template>

<style scoped lang="scss">
@import "../system.scss";
</style>
